import Vue from 'vue'
import Vuex from 'vuex'
import { loginByCorp, logout, getRolesByNopermission, getInfo, getPromises } from '@/api/login'
import { getExportTaskList } from '@/api/common'
import { setCorp, removeCorp, setToken, removeToken } from '@/utils/auth'
import router from '@/router';
import { MessageBox } from 'element-ui'

Vue.use(Vuex)

const state = {
	token: '',
	avatar: '',
    roles: [],
    cur_roles: {},
    permissions: [],
	userInfo: {},
    corp: {},
    corp_id: '',
	isAdmin: false,  //是否为一级账号/系统权限
	taskList: [],
    interval: null,
    isRunning: false
}

const mutations = {
	SET_TOKEN(state, token) {
		state.token = token
	},
	SET_USERINFO(state, userInfo) {
		state.userInfo = userInfo
	},
	SET_CURRENTROLES(state, cur_roles) {
		state.cur_roles = cur_roles
	},
	SET_AVATAR(state, avatar) {
		state.avatar = avatar
	},
	SET_ROLES(state, roles) {
		state.roles = roles
	},
	SET_PERMISSIONS(state, permissions) {
		state.permissions = permissions
	},
	SET_CORP(state, corp) {
		state.corp = corp
	},
	SET_CORPID(state, corpId) {
		state.corpId = corpId
	},
	SET_ISADMIN(state, isAdmin) {
		state.isAdmin = isAdmin
	},
	SET_TASKLIST(state, tasks) {
		state.taskList = tasks
	},
	SET_INTERVAL(state, interval) {
		state.interval = interval;
	},
	SET_RUNNING(state, status) {
		state.isRunning = status;
	}
}

const actions = {
	// 登录
	async Login({commit}, corp_id){
		const res = await loginByCorp({corp_id})
		if (res.data.Token) {
			setToken(res.data.Token)
			commit('SET_TOKEN', res.data.Token)
			const user = res.data.user
			commit('SET_CORP', res.data.corp)
			commit('SET_CORPID', res.data.corp.id)
			commit('SET_USERINFO', user)
			return res
		}
	},
	// 获取用户信息
	async GetUserInfo({commit, dispatch}){
		const res = await getInfo()
		if (res.code === 997){
			let htmlDom = '<div>'+
							'<p>您的账号已到期，为了不影响正常使用，请及时购买续费。</p>'+
							'<div style="display:flex;align-items:center;flex-direction:column;margin-top:20px;gap:10px;">'+
								'<img style="width:150px;height:150px;" src="https://anhuiyaoying.com/jiecunyun/tmall_code.png" alt="" />'+
								'<span style="color: #999;">打开手机淘宝 点击左上角扫一扫购买</span>'
							'</div>'+
						'</div>'
			MessageBox.confirm(htmlDom, '提示', {
				dangerouslyUseHTMLString: true,
				confirmButtonText: '确定',
				showCancelButton: false,
				closeOnClickModal: false,
				closeOnPressEscape: false
			}).then(() => {
				dispatch('FedLogOut')
				router.push('login')
			}).catch(() => {
				dispatch('FedLogOut')
				router.push('login')
			});
			return
		}

		let avatar = res.data.image_show&&res.data.image_show.url ? res.data.image_show.url : 'https://anhuiyaoying.com/default.png'
		commit('SET_AVATAR', avatar)
		commit('SET_CORP', res.data.corp_info)
		commit('SET_CORPID', res.data.corp_info.id)
		setCorp(res.data.corp_info.id)
		commit('SET_USERINFO', res.data);
		let level = (res.data.level == '一级账户')
		commit('SET_ISADMIN', level)
	},
	// 获取用户角色信息
	async GetRoleInfo({commit}){
		const res = await getRolesByNopermission()
		let roles = res.data.data.role_list
		commit('SET_ROLES', roles)
	},
	// 获取权限列表
	async GetPromises({commit, state}){
		const res = await getPromises({corp_id: state.corpId})
		let permissions = res.data
		if (permissions.length===1 && permissions[0]=='*'){
			commit('SET_PERMISSIONS', permissions)
		}else{
			commit('SET_PERMISSIONS', permissions.map(item => item.permission_value))
		}
	},
	// 获取任务列表
	async GetTaskList({commit}, corp){
		const res = await getExportTaskList({ corp })
		let tasks = res.data
		commit('SET_TASKLIST', tasks)
	},
	// 开启定时器
	startInterval({ commit, dispatch, state }) {
		// debugger
		if (!state.isRunning) {
			const interval = setInterval(() => {
				let flag = refreshTask(state.taskList)
				if (flag){
					dispatch('GetTaskList', state.corpId)
				}else{
					dispatch('removeInterval')
				}
			}, 1500);
			commit('SET_INTERVAL', interval);
			commit('SET_RUNNING', true);
		}
	},
	// 暂停定时器
	pauseInterval({ commit, state }) {
		if (state.isRunning) {
			clearInterval(state.interval);
			commit('SET_RUNNING', false);
		}
	},
	// 重启定时器
	resumeInterval({ dispatch, state }) {
		if (!state.isRunning) {
			dispatch('startInterval');
		}
	},
	// 清除定时器
	removeInterval({ commit, state }) {
		clearInterval(state.interval);
		commit('SET_RUNNING', false);
		commit('SET_INTERVAL', null);
	},
	// 退出系统
	async FedLogOut({ commit }){
		commit('SET_TOKEN', '')
		commit('SET_ROLES', [])
		commit('SET_PERMISSIONS', [])
		commit('SET_CORP', {})
		commit('SET_CORPID', null)
		removeCorp()
		removeToken()
	}
}

// 刷新任务状态
function refreshTask(lists) {
	let flag = false
	for (let index = 0; index < lists.length; index++) {
		const item = lists[index];
		if (!item.success_time_unix){
			flag = true
			break
		}
	}
	return flag
}

export default new Vuex.Store({
	state,
	actions,
	mutations,
})
